package com.ks.test;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * MD5加密类
 * 
 * @author 陈冬敏
 * @data 2013-4-9
 * 
 */
public class UtilEncryption {

	private static Log logger = LogFactory.getLog(UtilEncryption.class);

	private final static String ERROR_MESSAGE = "加密出错!";

	private final static String ALGORITHM = "MD5";

	private final static char HEXDIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public final static String toMD5(String s) {
		if (StringUtils.isBlank(s)) {
			return s;
		}
		byte[] strArray = s.getBytes();
		
		if (null == strArray)
			return null;
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance(ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			logger.error(ERROR_MESSAGE, e);
		}
		messageDigest.update(strArray);
		byte[] md = messageDigest.digest();
		int j = md.length;
		char str[] = new char[j * 2];
		int k = 0;
		for (int i = 0; i < j; i++) {
			byte byte0 = md[i];
			str[k++] = HEXDIGITS[byte0 >>> 4 & 0xf];
			str[k++] = HEXDIGITS[byte0 & 0xf];
		}
		return new String(str);
	}

	public static String EncryptSHA1(String strSrc) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		MessageDigest md = null;
		String strDes = null;
		String encName = "SHA-1";
		byte[] bt = null;
		try {
			bt = strSrc.getBytes("UTF-16LE");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			/*if (encName == null || encName.equals("")) {
				encName = "MD5";
			}*/
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex1(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}
	
	
	public static String bytes2Hex1(byte[] digest){
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<digest.length; i++) {
	       // System.out.printf("%x", digest[i]); System.out.print(" ");
			sb.append(String.format("%x", digest[i]));
	    }
		return sb.toString();
	}
	
	public static String bytes2Hex(byte[]bts) {
        String des="";
        String tmp=null;
        for (int i=0;i<bts.length;i++) {
                   tmp=(Integer.toHexString(bts[i] & 0xFF));
                   if (tmp.length()==1) {
                       des+="0";
                   }
                   des+=tmp;
               }
               return des;
       }

	public final static String toMD5(String s, String append) {
		return toMD5(s + append);
	}

	

}